import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import router from 'umi/router';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/lib/form';

import {
    Card,
    Row,
    Col,
    Button,
    Input,
    Select,
    message,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import DeliveryFee from './components/DeliveryFee';
import UserToTake from './components/UserToTake';
import UserToTakeTimeout from './components/UserToTakeTimeout';
import CouriersTimeout from './components/CouriersTimeout';
import CabinetRegister from './components/CabinetRegister';
import ShelvesToHeap from './components/ShelvesToHeap';
import DiscountSetting from './components/DiscountSetting';
import BuckleIntegral from './components/BuckleIntegral';

const { Option } = Select;
const { Item } = Form;
interface CabinetPlansAddProps extends FormComponentProps {
    dispatch: Dispatch;
    location: { query: any };
    detailInfo: any;
}

// 费用设置最大值: 500分，100%
const maxCents = 500, maxPercentage = 100;

@connect(({ cabinetPlansAdd: { detailInfo } }: any) => ({ detailInfo }))

class CabinetPlansAddElem extends Component<CabinetPlansAddProps> {
    componentDidMount() {
        const { location: { query: { id } } } = this.props;
        if (id) this.fetchDetailInfo(id);
    }

    componentDidUpdate(prevProps: any) {
        const { location: { query: { id } } } = this.props;
        if (id && prevProps.location.query.id !== id) {
            this.fetchDetailInfo(id);
        }
    }

    componentWillUnmount() {
        this.fetchAction('clear');
    }

    fetchDetailInfo = (id: number) => {
        const { dispatch } = this.props;
        dispatch({
            type: 'cabinetPlansAdd/fetch',
            payload: { id },
        });
    }

    handleSubmit = () => {
        const { form: { validateFieldsAndScroll } } = this.props;
        validateFieldsAndScroll((errors, values) => {
            if (errors) return;

            const patn = /[`~!@#$%^&*()_\-+=<>?:"{}|,.\\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g;
            if (patn.test(values.name)) {
                message.error('请勿输入特殊字符');
            } else {
                const { location: { query } } = this.props;
                const params = { ...query, ...values };
                this.fetchAction('saveOrUpdate', params);
            }
        });
    }

    fetchAction = (typeName: string, payload: any = {}) => {
        const { dispatch } = this.props;
        dispatch({
            type: `cabinetPlansAdd/${typeName}`,
            payload,
        });
    }

    render() {
        const { form: { getFieldDecorator }, detailInfo } = this.props;

        return (
            <Fragment>
                <PageHeader />

                <Form hideRequiredMark className="tableListForm">
                    <Card title="基本信息" bordered={false}>
                        <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
                            <Col md={8} sm={24}>
                                <Item label="套餐名称">
                                    {getFieldDecorator('name', ({
                                        initialValue: detailInfo.name,
                                        rules: [{ required: true, message: '请输入套餐名称' }],
                                    }))(
                                        <Input allowClear placeholder="请输入" />,
                                    )}
                                </Item>
                            </Col>
                            <Col md={8} sm={24}>
                                <Item label="　　状态">
                                    {getFieldDecorator('valid', ({
                                        initialValue: detailInfo.valid || 1,
                                        rules: [{ required: true, message: '请选择状态' }],
                                    }))(
                                        <Select>
                                            <Option value={1}>有效</Option>
                                            <Option value={0}>无效</Option>
                                        </Select>,
                                    )}
                                </Item>
                            </Col>
                        </Row>
                    </Card>

                    <DeliveryFee
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <UserToTake
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <UserToTakeTimeout
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <CouriersTimeout
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <CabinetRegister
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <ShelvesToHeap
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <DiscountSetting
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />
                    <BuckleIntegral
                        getFieldDecorator={getFieldDecorator}
                        detailInfo={detailInfo}
                        maxCents={maxCents}
                        maxPercentage={maxPercentage}
                    />

                    <Card bordered={false} style={{ marginTop: -12 }}>
                        <Button
                            type="primary"
                            onClick={this.handleSubmit}
                        >提交
                        </Button>
                        <Button
                            type="primary"
                            className="marginL16"
                            ghost
                            onClick={router.goBack}
                        >取消
                        </Button>
                    </Card>
                </Form>
            </Fragment>
        );
    }
}

export default Form.create<CabinetPlansAddProps>()(CabinetPlansAddElem);
